# -*- coding: utf-8 -*-

# __date:       2021/6/30
# __author:     Yang Chao
# __function:   Reverse Integer 整数反转

class Solution:

    def reverse1(self, x: int) -> int:
        """
        解法一：暴力法，将字符串反转，再转化为相应的数字
        :param x:
        :return:
        """
        sign = 1
        if x < 0:
            x = abs(x)
            sign = -1
        res = int(str(x)[::-1]) * sign
        if -2 ** 31 <= res <= 2**31 - 1:
            return res
        return 0

    def reverse2(self, x: int) -> int:
        """
        解法二：数学公式法，将余数保存到一个列表中，在重新遍历累加获取新的数
        :param x:
        :return:
        """
        sign = 1
        if x < 0:
            x = abs(x)
            sign = -1
        li = []
        while x > 0:
            x, temp = divmod(x, 10)
            li.append(temp)
        length = len(li) - 1
        res = 0
        for n in li:
            res += 10 ** length * n
            length -= 1
        res *= sign
        if -2 ** 31 < res < 2**31 - 1:
            return res
        return 0

    def reverse3(self, x: int) -> int:
        """
        解法三：对第二种解法的优化过程
        :param x:
        :return:
        """
        sign = 1
        res = 0
        if x < 0:
            x = abs(x)
            sign = -1
        while x > 0:
            x, temp = divmod(x, 10)
            res = res * 10 + temp
        res *= sign
        if -2 ** 31 < res < 2 ** 31 - 1:
            return res
        return 0